const std = @import("std");
const api = @import("api.zig");
const memory = @import("memory.zig");
const cpu = @import("cpu.zig");
const trap = @import("trap.zig");
const caps = @import("caps.zig");
const gpu = @import("gpu.zig");
const display = @import("display.zig");
const ui_comm = @import("ui_comm.zig");
const driver_manager = @import("driver_manager.zig");
const kotlin_native_ffi = @import("kotlin_native_ffi.zig");

// Exokernel 主结构体
pub const Exokernel = struct {
    memory_manager: memory.MemoryManager,
    cpu_manager: cpu.CpuManager,
    trap_handler: trap.TrapHandler,
    capability_manager: caps.CapabilityManager,
    driver_manager: driver_manager.DriverManager,
    gpu_manager: gpu.GpuManager,
    display_manager: display.DisplayManager,
    ui_comm_manager: ui_comm.UICommManager,

    // 初始化 exokernel
    pub fn init(allocator: std.mem.Allocator) !Exokernel {
        // 先初始化基础管理器
        const memory_manager = try memory.MemoryManager.init(allocator);
        const cpu_manager = cpu.CpuManager.init();
        const trap_handler = try trap.TrapHandler.init(allocator);
        const capability_manager = caps.CapabilityManager.init(allocator);
        
        // 使用基础管理器初始化驱动管理器
        const driver_manager_instance = try driver_manager.DriverManager.init(
            allocator,
            @constCast(&memory_manager),
            @constCast(&capability_manager),
            @constCast(&trap_handler)
        );
        
        var kernel = Exokernel{
            .memory_manager = memory_manager,
            .cpu_manager = cpu_manager,
            .trap_handler = trap_handler,
            .capability_manager = capability_manager,
            .driver_manager = driver_manager_instance,
            .gpu_manager = try gpu.GpuManager.init(allocator),
            .display_manager = try display.DisplayManager.init(allocator),
            .ui_comm_manager = try ui_comm.UICommManager.init(allocator),
        };

        // 初始化硬件抽象
        try kernel.initHardware();

        return kernel;
    }

    // 初始化硬件
    fn initHardware(self: *Exokernel) !void {
        // 设置内存映射
        try self.memory_manager.setupMemoryMap();

        // 初始化CPU控制结构
        self.cpu_manager.initControlRegisters();

        // 设置中断处理
        try self.trap_handler.setupInterrupts();

        // 初始化能力系统
        try self.capability_manager.initRootCapabilities();
        
        // 初始化全局GPU和显示管理器实例
        gpu.global_gpu_manager = self.gpu_manager;
        display.global_display_manager = self.display_manager;
        
        // 初始化UI通信管理器
        ui_comm.global_ui_comm_manager = self.ui_comm_manager;
        _ = self.ui_comm_manager.initialize();
        
        // 初始化Kotlin/Native FFI
        try kotlin_native_ffi.init_ffi();
    }

    // 启动exokernel
    pub fn start(self: *Exokernel) !void {
        std.log.info("Exokernel started. Welcome to ZENrs!", .{});

        // 进入服务层启动阶段
        try self.prepareServiceLayer();
    }

    // 为服务层准备环境
    fn prepareServiceLayer(self: *Exokernel) !void {
        // 创建初始能力
        const mem_cap = try self.capability_manager.createCapability(
            .{ .type = .memory, .size = 0x1000000 }, // 16MB 初始内存
        );
        const cpu_cap = try self.capability_manager.createCapability(
            .{ .type = .cpu, .priority = 10 },
        );
        
        // 创建GPU和显示相关能力
        const io_cap = try self.capability_manager.createCapability(
            .{ .type = .io, .port_range = .{ .start = 0, .end = 0xFFFF } },
        );

        // 记录能力ID以便服务层获取
        self.capability_manager.setServiceLayerCapabilities(mem_cap, cpu_cap);
        
        // 使用IO能力
        _ = io_cap;
        
        // 设置初始显示模式（使用第一个显示设备的第一个模式）
        if (self.display_manager.devices.items.len > 0) {
            const device_id = self.display_manager.devices.items[0].id;
            if (self.display_manager.devices.items[0].modes.items.len > 0) {
                _ = self.display_manager.setDisplayMode(device_id, 0);
            }
        }
    }

    // 清理资源
    pub fn deinit(self: *Exokernel, allocator: std.mem.Allocator) void {
        // 先清理驱动管理器
        self.driver_manager.deinit();
        
        // 然后清理其他管理器
        self.memory_manager.deinit(allocator);
        self.trap_handler.deinit();
        self.capability_manager.deinit(allocator);
        self.gpu_manager.deinit();
        self.display_manager.deinit();
        // UI通信管理器资源在服务层关闭时释放
        // 清理Kotlin/Native FFI资源
        kotlin_native_ffi.deinit_ffi();
    }
};

// 主入口点（用于独立测试）
pub fn main() !void {
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    const allocator = gpa.allocator();
    defer _ = gpa.deinit();

    var kernel = try Exokernel.init(allocator);
    defer kernel.deinit(allocator);

    try kernel.start();

    // 进入待机状态（实际系统中会进入服务层）
    std.log.info("Exokernel entering idle state...", .{});
    while (true) {
        cpu.CpuManager.idle();
    }
}